<?php

/**
 * This is the model class for table "public.page".
 */
require_once(dirname(__FILE__).'/base/PageBase.php');
Yii::import('application.modules.User.models.User');

class Page extends PageBase
{
	const STATUS_DEACTIVE = 0, STATUS_ACTIVE = 1;
    const TYPE_CMS = 'cms', TYPE_STANDARD = 'standard',TYPE_GROUP= 'group';
	
    public $urls;
    
    public $selectedWorkflowId;

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            array('site_id, title, alias, type, route, view', 'required'),
            array('css_files, js_files, title, alias, revision_id, template_content_id, workflow_id, revised_by, creation_datetime, last_update, status, defaultUrl', 'safe'),
            array('id, revision_id, site_id, template_content_id, css_files, workflow_id, revised_by, creation_datetime, last_update, js_files, title, alias, status, type, route, view', 'safe', 'on'=>'search'),
            array('selectedWorkflowId, title, alias, status', 'safe', 'on'=>'searchByWorkflow'),
        );
    }
    
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        return array(
            'pageWidgets' => array(self::HAS_MANY, 'PageWidget', 'page_id', 'order' => '"pageWidgets"."container","pageWidgets"."ordering"'),
            'pageUrls' => array(self::HAS_MANY, 'PageUrl', 'page_id'),
            'pages' => array(self::HAS_MANY, 'Page', 'revision_id'),
            'site' => array(self::BELONGS_TO, 'Site', 'site_id'),
            'workflow' => array(self::BELONGS_TO, 'Workflow', 'workflow_id'),
            'revisedBy' => array(self::BELONGS_TO, 'User', 'revised_by'),
            'defaultUrl' => array(self::HAS_ONE, 'PageUrl', 'page_id', 'on' => '"defaultUrl"."default" = true'),
            'parent'=>array(self::BELONGS_TO, 'Page', 'parent_id'),
            'children'=>array(self::HAS_MANY, 'Page', 'parent_id', 'order'=>'ordering'),
            'countChildren'=>array(self::STAT, 'Page', 'parent_id'),
            'revisions'=>array(self::HAS_MANY, 'PageRevision', 'page_id'),
            'currentRevisions'=>array(self::HAS_MANY, 'PageCurrentRevision', 'page_id'),
        );
    }
    
    public function behaviors()
    {
        return array(
            'timestamp'=>array(
                'class'=>'TimestampBehavior',
            ),
        );
    }
    
    public function getStatusOptions()
    {
        return array(
            self::STATUS_DEACTIVE => 'Deactive',
            self::STATUS_ACTIVE => 'Active',
        );
    }
    
    public function getStatusText()
    {
        $options = $this->getStatusOptions();
        return isset($options[$this->status]) ? $options[$this->status] : Yii::t('app', 'Unknown {att}', array('{att}'=>$this->status));
    }
    
    public function getTypeOptions()
    {
        return array(
            self::TYPE_CMS => 'CMS',
            self::TYPE_STANDARD => 'Standard',
            self::TYPE_GROUP => 'Group',
        );
    }
    
    public function getTypeText()
    {
        $options = $this->getTypeOptions();
        return isset($options[$this->type]) ? $options[$this->type] : Yii::t('app', 'Unknown {att}', array('{att}'=>$this->type));
    }
    
     public function getTemplateOptions()
    {
        $models = FSM::run('Cms.Template.getList')->models;
        if (count($models))
            return CHtml::listData($models, 'id', 'name');
        return array();
    }
    
 	public function getTemplateContentOptions()
    {
        $models = FSM::run('Cms.TemplateContent.getList')->models;
        if (count($models))
        {
            $items = array();
            foreach ($models as $model)
            {
                if (is_object($model->template))
                    $items[$model->id] = $model->template->name.' - revision '.$model->revision_id;
            }
            return $items;
        }
        return array();
    }
    
    public function getSiteOptions()
    {
        $models = FSM::run('Cms.Site.getList')->models;
        if (count($models))
            return CHtml::listData($models, 'id', 'name');
        return array();
    }
    
    public function getUserOptions()
    {
		$models = FSM::run('User.User.getList')->models;
        if (count($models))
            return CHtml::listData($models, 'id', 'username');
        return array();
    }
    
    public function search()
    {
        $criteria=new CDbCriteria;
        $criteria->with = array(
            'defaultUrl'=>array(
                'select'=>'url',
            ),
        );

        $criteria->compare('id',$this->id,true);
        $criteria->compare('t.site_id',$this->site_id);
        $criteria->addSearchCondition('title',$this->title, true, 'AND', 'LIKE');
        $criteria->addSearchCondition('alias',$this->alias, true, 'AND', 'LIKE');
        $criteria->addSearchCondition('"defaultUrl".url',$this->defaultUrl, true, 'AND', 'LIKE');
        
        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'sort'=>array(
                'defaultOrder'=>'t.title',
                'attributes'=>array(
                    'title',
                    'alias',
                    'creation_datetime',
                    'last_update',
                    'defaultUrl'=>array(
                        'asc'=>'"defaultUrl".url ASC',
                        'desc'=>'"defaultUrl".url DESC',
                    )
                )
            ),
            'pagination'=>array(
                'pageSize'=>Settings::BO_PAGE_SIZE,
            ),
        ));
    }
    
    protected function beforeSave() {
        // make the template alias
        if (empty($this->alias))
            $this->alias = toSlug($this->title);
        return parent::beforeSave();
    }
    
    public function getLastestRevision()
    {
        $criteria = new CDbCriteria();
        $criteria->compare('page_id', $this->id);
        $criteria->order = 'id DESC';
        return PageRevision::model()->find($criteria);
    }
    
    public function getPath($pageId)
    {
        if(($cache=Yii::app()->cache)!==null)
        {
            $key=__CLASS__.'::'.__FUNCTION__.'#$pageId'.$pageId;
            if(($data=$cache->get($key))!==false)
            {
                return unserialize($data);
            }
        }
        $path = $this->getFullPath($pageId);
        
        if(isset($cache))
        {
            $sql = "SELECT last_update FROM ".SITE_TABLE_PREFIX."page ORDER BY last_update DESC LIMIT 1;";
            $dependency = new CDbCacheDependency($sql);
            $cache->set($key,serialize($path), 900, $dependency);
        }
        
        return $path;
    }
    
    protected function getFullPath($pageId)
    {
        static $path;
        if (!isset($path)) $path = array($pageId);
        $model = Page::model()->findByPk($pageId);
        if (is_object($model))
        {
            array_push($path, $model->parent_id);
            $this->getFullPath($model->parent_id);
        }
        return array_reverse($path);
    }
    
    public function searchByWorkflow()
    {
        $criteria = new CDbCriteria();
        $criteria->join = 'INNER JOIN "public"."'.SITE_TABLE_PREFIX.'page_current_revision" "pcr" ON pcr.page_id = t.id';
        $criteria->compare('pcr.workflow_id',$this->selectedWorkflowId);
        $criteria->addInCondition('t.type',array('cms','standard'));
        
        $criteria->compare('t.title',$this->title,true);
        $criteria->compare('t.alias',$this->alias,true);
        $criteria->compare('t.status',$this->status);
        
        $criteria->order = 't.id ASC';
        
        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'pagination'=>false,
            'sort'=>array(
                //'defaultOrder'=>'t.title',
                'attributes'=>array(
                    /*'title',
                    'alias',
                    'creation_datetime',
                    'last_update',
                    'defaultUrl'=>array(
                        'asc'=>'"defaultUrl".url ASC',
                        'desc'=>'"defaultUrl".url DESC',
                    )*/
                )
            ),
        ));
    }
}
